package com.coupon.distribution.vo;

import com.coupon.common.constant.PeriodTypeEnum;
import com.coupon.distribution.constant.CouponStatusEnum;
import com.coupon.distribution.entity.Coupon;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName CouponClassify.java
 * @create 2023年06月26日 下午7:52
 * @Description 用户优惠券分类: 根据优惠券状态
 * @Version V1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CouponClassify {
    // 可用的
    private List<Coupon> usable;
    // 已使用的
    private List<Coupon> used;
    // 过期的
    private List<Coupon> expired;

    public static CouponClassify classify(List<Coupon> coupons) {
        List<Coupon> usable = new ArrayList<>(coupons.size());
        List<Coupon> used = new ArrayList<>(coupons.size());
        List<Coupon> expired = new ArrayList<>(coupons.size());

        coupons.forEach(c ->{
            // 判断优惠券是否过期
            boolean isTimeExpire = false;
            long curTime = System.currentTimeMillis();
            if (c.getCouponTemplateSDK().getRule().getExpiration().getPeriod()
                    .equals(PeriodTypeEnum.REGULAR.getCode())) {
                isTimeExpire = c.getCouponTemplateSDK().getRule().getExpiration().getDeadline() <= curTime;
            }else if (c.getCouponTemplateSDK().getRule().getExpiration().getPeriod()
                    .equals(PeriodTypeEnum.SHIFT.getCode())) {
                isTimeExpire = DateUtils.addDays(
                        c.getAssignTime(),
                        c.getCouponTemplateSDK().getRule().getExpiration().getGap()
                ).getTime() <= curTime;
            }

            if (c.getStatus() == CouponStatusEnum.USED) {
                used.add(c);
            }else if (c.getStatus() == CouponStatusEnum.EXPIRED || isTimeExpire) {
                expired.add(c);
            } else {
                usable.add(c);
            }
        });

        return new CouponClassify(usable, used, expired);
    }

}
